package vip.xiaonuo.client.modular.examPaper.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import vip.xiaonuo.client.modular.examPaper.entity.ClientExamPaper;
import vip.xiaonuo.client.modular.examPaper.mapper.ClientExamPaperMapper;
import vip.xiaonuo.client.modular.examPaper.param.ClientExamPaperPageParam;
import vip.xiaonuo.client.modular.examPaper.service.ClientExamPaperService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.enums.CommonStatusEnum;
import vip.xiaonuo.common.enums.CommonYesNoEnum;
import vip.xiaonuo.common.page.CommonPageRequest;

@Service
@AllArgsConstructor
public class ClientExamPaperServiceImpl extends ServiceImpl<ClientExamPaperMapper, ClientExamPaper> implements ClientExamPaperService {


    public Page<ClientExamPaper> page(ClientExamPaperPageParam examPaperPageParam) {
        QueryWrapper<ClientExamPaper> queryWrapper = new QueryWrapper<ClientExamPaper>().checkSqlInjection();
        String now = DateUtil.now();
        queryWrapper.lambda().le(ClientExamPaper::getStartDate, now);
        queryWrapper.lambda().ge(ClientExamPaper::getEndDate, now);
        queryWrapper.lambda().eq(ClientExamPaper::getOnlyForExamHall, CommonYesNoEnum.NO.getCode());
        queryWrapper.lambda().eq(ClientExamPaper::getStatus, CommonStatusEnum.ZC.getCode());
        if (ObjectUtil.isNotEmpty(examPaperPageParam.getPaperName())) {
            queryWrapper.lambda().like(ClientExamPaper::getPaperName, examPaperPageParam.getPaperName());
        }
        if (ObjectUtil.isNotEmpty(examPaperPageParam.getCategoryId())) {
            queryWrapper.lambda().eq(ClientExamPaper::getCategoryId, examPaperPageParam.getCategoryId());
        }
        if (ObjectUtil.isAllNotEmpty(examPaperPageParam.getSortField(), examPaperPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(examPaperPageParam.getSortOrder());
            queryWrapper.orderBy(true, examPaperPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(examPaperPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ClientExamPaper::getId);
        }
        Page<ClientExamPaper> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        page.getRecords().forEach(item -> item.setSelectionConfig(null));
        return page;
    }


}
